/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-10-03     FuLei       the first version
 */

#include <mypwm.h>

#define PWM1_CH1        1
#define PWM2_CH2        2
#define PWM4_CH4        4

struct rt_device_pwm *dev_pwm1 = RT_NULL;
struct rt_device_pwm *dev_pwm2 = RT_NULL;
struct rt_device_pwm *dev_pwm4 = RT_NULL;


int PWM1_Init(void)
{
    int ret = RT_EOK;
    dev_pwm1 = (struct rt_device_pwm *)rt_device_find("pwm1");
    if(dev_pwm1 == RT_NULL)
    {
        rt_kprintf("not find pwm1 ...\n");
        ret = -RT_ERROR;
    }

//    rt_pwm_set(dev_pwm1, PWM1_CH1, 50*1000*1000, 50*1000*1000/5);   // para3:/* 周期为5ms，单位为纳秒ns */, para4: 脉冲宽度 单位为纳秒ns
//    rt_pwm_enable(dev_pwm1, PWM1_CH1);
    return ret;
}

void PWM1_CH1_Set(rt_uint32_t period,rt_uint32_t pulse, FunctionalState state)
{
    if(state != ENABLE)
    {
        rt_pwm_disable(dev_pwm1, PWM1_CH1);
        return;
    }
    rt_pwm_set(dev_pwm1, PWM1_CH1, period, pulse);  // /*单位为纳秒ns */
    rt_pwm_enable(dev_pwm1, PWM1_CH1);
}
void PWM1_CLOSE(void)
{
    rt_pwm_disable(dev_pwm1, PWM1_CH1);
}
//============================================
int PWM2_Init(void)
{
    int ret = RT_EOK;
    dev_pwm2 = (struct rt_device_pwm *)rt_device_find("pwm2");
    if(dev_pwm2 == RT_NULL)
    {
        rt_kprintf("not find pwm2 ...\n");
        ret = -RT_ERROR;
    }

    rt_pwm_set(dev_pwm2, PWM2_CH2, 500*1000*1000, 500*1000*1000/5);   // para3:/* 周期为5ms，单位为纳秒ns */, para4: 脉冲宽度 单位为纳秒ns
    rt_pwm_enable(dev_pwm2, PWM2_CH2);
    return ret;
}

void PWM2_CH2_Set(rt_uint32_t period,rt_uint32_t pulse,FunctionalState state)
{
//    if(state != ENABLE)
//    {
//        rt_pwm_disable(dev_pwm1, PWM1_CH1);
//        return;
//    }
    rt_pwm_set(dev_pwm2, PWM2_CH2, period, pulse);  // /*单位为纳秒ns */
    rt_pwm_enable(dev_pwm2, PWM2_CH2);
}

//============================================


int PWM4_Init(void)
{
    int ret = RT_EOK;
    dev_pwm4 = (struct rt_device_pwm *)rt_device_find("pwm4");
    if(dev_pwm4 == RT_NULL)
    {
        rt_kprintf("not find pwm4 ...\n");
        ret = -RT_ERROR;
    }
    rt_pwm_set(dev_pwm4,PWM4_CH4,8333000,0);
    rt_pwm_disable(dev_pwm4, PWM4_CH4);
    return ret;
}

void PWM4_CH4_Set(rt_uint32_t period,rt_uint32_t pulse,FunctionalState state)
{
//    if(state != ENABLE)
//    {
//        rt_pwm_disable(dev_pwm4, PWM4_CH4);
//        return;
//    }
    rt_pwm_set(dev_pwm4, PWM4_CH4, period, pulse);
    rt_pwm_enable(dev_pwm4, PWM4_CH4);
}
